$(function() {
	var skyeye_setting = [];
	var skyeyeAnnotate = function(ele, opt) {
		this.defaults = { //defaults 是我们设置的默认参数。
			id: null,
			width: '240', //批注默认宽度
			addAnnotate: true, //是否可以添加新的批注
			edit: true, //是否可以编辑
			userName: 'skyeye', //添加批注的人
			userImage: 'skyeye-editor/images/no-userphoto.png', //添加批注人的logo
			data: [], //默认回显的数据
			addIconSrc: 'skyeye-editor/images/add-icon.png', //新增批注的图标
			whetherLoadData: false, //是否已经加载数据，根据数据的数量进行判断
			resetContentBox: true, //是否重置左侧内容宽度
			annotateId: null, //右侧批注的id
			notChooseBgColor: '#fef7a9', //选中内容未处于编辑状态的颜色
			inChooseBgColor: '#fdf05d', //选中内容处于编辑状态的颜色
		};
		this.settings = $.extend({}, this.defaults, opt);
	}
	skyeyeAnnotate.prototype = {
		_id: null,
		_op: null,
		$this: null,
		tagName: 'mark',
		_showEditBoxZIndex: 99999,
		init: function() {
			_id = this.settings.id;
			$this = $("#" + _id);
			_op = this;
			this.create();
		},

		// 加载事件
		create: function() {
			var setting = getObject(_id);
			// 空白处点击事件
			$(document).click(function(event) {
				if($((event.target || event.srcElement)).closest(".show-editor,#annotateIcon,.show-content").length == 0) {
					// 过滤非加载项
					var setting = getObject(_id);
					if($("#" + setting.annotateId) && $("#" + setting.annotateId).length > 0) {
						// 移除标注box选中的特效
						$("#" + setting.annotateId).find(".new-skyeye-anno-box").removeClass("hover");
						_op.resetData(true);
						$this.find(".selectClass").css({
							"background-color": setting.notChooseBgColor,
							"border": "1px solid transparent"
						});
					}
					$('#skyeyeLine').parent().remove();
				}
			});

			if(setting.addAnnotate){
				$this.mouseup(function(e) {
					var selectedText = _op.getSelectText();
					var addIconSrc = 'skyeye-editor/images/add-icon.png';
					if(getObject(_id).addIconSrc) {
						addIconSrc = getObject(_id).addIconSrc;
					}
					$("#annotateIcon").unbind("click");
					var addIcon = '<div id="annotateIcon" style="display: none; position: absolute;" title="添加批注"><img src="' + addIconSrc + '" class="skyeyetipsIcon filter"></div>';
					$this.append(addIcon);
					if(selectedText) {
						$("#annotateIcon").css({
							"left": e.pageX + 1,
							"top": e.pageY - 30
						}).fadeIn(300);
						_op.addAnnotateIcon();
					} else {
						$this.find("div[id='annotateIcon']").remove();
					}
				});
			}
			
			// 初始化数据
			_op.initData();
		},

		// 添加批注按钮事件
		addAnnotateIcon: function() {
			$("#annotateIcon").hover(function() {
				$(this).children().removeClass("filter");
			}, function() {
				$(this).children().addClass("filter");
			}).click(function() {
				$("#annotateIcon").unbind("click");
				$this.find("div[id='annotateIcon']").remove();
				_op.addAnnoTate();
			});
		},

		// 添加批注
		addAnnoTate: function() {
			// 1.加载右侧box
			_op.resetAddAnnotateBox();
			// 2.添加批注框
			_op.addAnnotateBox();
		},

		// 添加右侧box
		resetAddAnnotateBox: function() {
			var setting = getObject(_id);
			// 判断是否需要重新加载批注宽度设置内容的宽度
			if(!setting.whetherLoadData) {
				if(setting.resetContentBox) {
					// 设置当前content的宽度
					var con_width = $this.outerWidth(true);
					var annoTate_width = parseInt(setting.width);
					$this.css({
						"width": (con_width - annoTate_width - 20) + 'px'
					});
				}
				$this.css({
					"float": 'left'
				});
				var con_height = $this.height();
				// 获取批注框的大box的id
				var annotateId = _op.getRandomId();
				var annotateBox = '<div class="annotate-box" id="' + annotateId + '" style="width: ' + annoTate_width + 'px; height: ' + con_height + 'px;"></div>';
				$this.after(annotateBox);
				_op.setSettings(_id, {
					whetherLoadData: true,
					annotateId: annotateId
				});
				
				// 设置批注点击事件
				$("#" + annotateId).on("click", ".new-skyeye-anno-box", function(e){
					var _this = $(this);
					if(_this.hasClass("hover")){
						return false;
					}
					_op.resetData(false);
					var insId = _this.attr("insId");
					_op.setDomMation(insId);
					_this.css({
						"z-index": _op._showEditBoxZIndex
					});
					// 设置内容编辑
					_op.setContent2Edit(_this);
					return false;
				});
				
				// 批注内容添加点击事件
				$this.on("click", ".selectClass", function(e){
					_op.resetData(false);
					var insId = $.trim($(this).attr("class").replace("selectClass", ""));
					var _this = $(".annotate-box").find('div[insid="' + insId + '"]');
					_op.setDomMation(insId);
					if(_op.isPhoneResult()){
						// 手机端
						$('body').css('overflow', 'hidden');
						$('body').append(_op.getShowPhoneContentHtml(_this));
						$(".skyeye-shade").click(function(e){
							$(".show-phone-content").remove();
							$('body').css('overflow', 'auto');
						});
					}else{
						// 电脑端
						_this.css({
							"z-index": _op._showEditBoxZIndex
						});
						// 设置内容编辑
						_op.setContent2Edit(_this);
					}
					return false;
				});
			}
		},
		
		setDomMation: function(insId){
			var setting = getObject(_id);
			$this.find(".selectClass").css({
				"background-color": setting.notChooseBgColor,
				"border": "1px solid transparent"
			});
			// 设置内容背景颜色
			$("." + insId).css({
				"background-color": setting.inChooseBgColor,
				"border": "1px solid darkred"
			});
		},
		
		// 手机端展示获取dom信息
		getShowPhoneContentHtml: function(_this){
			var img = _this.find(".anno-user-img").attr("src");
			var userName = _this.find(".anno-user-name").html();
			var createTime = _this.find(".anno-time").html();
			var content = _this.find(".show-content").html();
			var strDom = '<div class="skyeye-shade show-phone-content"></div>';
			strDom += '<div class="skyeye-phone-dialog-btm show-phone-content">'
						+ '<div class="skyeye-title">'
							+ '<div class="img"><img src="' + img + '" /></div>'
							+ '<div class="userName">' + userName + '</div>'
							+ '<div class="createTime">' + createTime + '</div>'
						+ '</div>'
						+ '<div class="skyeye-content">' + content + '</div>'
					+ '</div>';
			return strDom;
		},
		
		// 判断是否是手机端
		isPhoneResult: function(){
			var pageSize = _op.getPageSize();
			if(pageSize[0] > 768){
				return false;
			}
			return true;
		},
		
		// 获取页面尺寸信息
		getPageSize: function(){
			var xScroll, yScroll;
		    if (window.innerHeight && window.scrollMaxY) {
		        xScroll = window.innerWidth + window.scrollMaxX;
		        yScroll = window.innerHeight + window.scrollMaxY;
		    } else {
		        if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac    
		            xScroll = document.body.scrollWidth;
		            yScroll = document.body.scrollHeight;
		        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari    
		            xScroll = document.body.offsetWidth;
		            yScroll = document.body.offsetHeight;
		        }
		    }
		    var windowWidth, windowHeight;
		    if (self.innerHeight) { // all except Explorer    
		        if (document.documentElement.clientWidth) {
		            windowWidth = document.documentElement.clientWidth;
		        } else {
		            windowWidth = self.innerWidth;
		        }
		        windowHeight = self.innerHeight;
		    } else {
		        if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode    
		            windowWidth = document.documentElement.clientWidth;
		            windowHeight = document.documentElement.clientHeight;
		        } else {
		            if (document.body) { // other Explorers    
		                windowWidth = document.body.clientWidth;
		                windowHeight = document.body.clientHeight;
		            }
		        }
		    }       
		    // for small pages with total height less then height of the viewport    
		    if (yScroll < windowHeight) {
		        pageHeight = windowHeight;
		    } else {
		        pageHeight = yScroll;
		    }    
		    // for small pages with total width less then width of the viewport    
		    if (xScroll < windowWidth) {
		        pageWidth = xScroll;
		    } else {
		        pageWidth = windowWidth;
		    }
		    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
		    return arrayPageSize;
		},
		
		// 设置内容编辑
		setContent2Edit: function($box){
			var setting = getObject(_id);
			$box.parent().find(".new-skyeye-anno-box").removeClass("hover");
			$box.addClass("hover");
			$box.find(".show-content").hide();
			$box.find(".show-editor").html($box.find(".show-content").html());
			$box.find(".show-editor").show();
			if(!setting.edit){
				// 不可以编辑
				$box.find(".show-editor").attr("contenteditable", false);
			}else{
				// 可以编辑
				$box.find(".show-editor").focus();
			}
			_op.setLineToBox($box.attr("insId"));
		},
		
		// 加载选中内容的连线
		setLineToBox: function(insId){
			$('#skyeyeLine').parent().remove();
			// 内容框
			var contentBox = $(".annotate-box").find('div[insid="' + insId + '"]')[0];
			// 文章中标记处
			var mark = $this.find('.' + insId);
			mark = mark[mark.length - 1];
			var pos1 = _op.getElCoordinate(mark, 'right');
			var pos2 = _op.getElCoordinate(contentBox, 'left');
			var posLocation = _op.getPos(pos1, pos2);
			var start = posLocation.start;
            var end = posLocation.end;
			$this.append('<svg class="lineWrap"><line x1="0" y1="0" x2="0" y2="0" stroke="dodgerblue" stroke-width="1" id="skyeyeLine"></line></svg>');
			$('#skyeyeLine').attr({x1: start.x, y1: start.y, x2: end.x, y2: end.y});
		},
		
		// 获取坐标元素,type展示类型，left:左侧，right:右侧
		getElCoordinate: function(dom, type) {
			var height = dom.offsetHeight;
			var width = dom.offsetWidth;
			var t = $(dom).offset().top + (height / 2);
			var l = $(dom).offset().left;
			var w = dom.offsetWidth;
			var h = dom.offsetHeight;
			if(type === 'left'){
			}else if(type === 'right'){
				l = l + width - 10;
			}
        	return {
            	top: t,//Y轴坐标
            	left: l,//X轴坐标
            	width: w,//元素宽度
            	height: h//元素高度 
        	};
    	},
    	
    	// 获取连线的起点和终点的位置
    	getPos: function(pos1, pos2) {
			// 分两种情况
			var x1, y1, x2, y2;
			x1 = pos1.left;
			y1 = pos1.top;
			x2 = pos2.left;
			y2 = pos2.top;
			return {
				start: {
					x: x1,
					y: y1
				},
				end: {
					x: x2,
					y: y2
				}
			}
		},

		// 添加批注框
		addAnnotateBox: function() {
			var setting = getObject(_id);
			var insId = (new Date().getTime());
			var selection = window.getSelection();
			var selData = _op.getSelData(_op.tagName, selection, insId);
			var boxId = _op.getRandomId();
			var top = ($("." + insId).offset().top - 80);
			if(top < 0){
				top = 0;
			}
			var box = _op.getNowSkyeyeAnnoBox({
				selectText: selData.content,
				startAdd: selData.startOffset,
				endAdd: selData.endOffset,
				textLength: length,
				annoId: boxId,
				insId: insId,
				userImage: setting.userImage,
				userName: setting.userName,
				annoTateContent: '',
				marginTop: top + 'px',
				createDate: _op.getNowDate()
			});
			$("#" + setting.annotateId).append(box);
			// 设置内容编辑
			_op.setContent2Edit($("#" + boxId));
		},
		
		getSelData: function(type, selection, insId, item){
			var data;
			if(selection.rangeCount > 0) {
				var range = selection.getRangeAt(0);
				var hasOneOffset = range.startContainer === range.endContainer && range.startOffset === range.endOffset;
				var targetElems = _op.createTag(_op.tagName, selection, insId);
				if(targetElems.length > 0) {
					if(item) {
						data = {
							content: item.selectText,
							endOffset: item.startAdd,
							length: item.endAdd,
							startOffset: item.textLength,
							points: [],
							key: insId,
							type: _op.tagName
						};
						_op._setElems(targetElems, data);
					} else {
						data = _op._getData(targetElems[0], targetElems[targetElems.length - 1]);
						data.content = hasOneOffset ? '缺漏' : data.content;
						data.points = type === 'exchange' ? this.innerData.points : [];
						data.key = insId;
						data.type = hasOneOffset ? 'missing' : type;
					}
				}
			}
			return data;
		},
		
		_setElems: function(elems, data) {
			if(elems && elems.length > 0) {
				var draw = data.type === 'exchange' ? _op._drawExchange(data) : null;
				elems.forEach(function(elem) {
					elem.setAttribute('markkey', data.key);
					elem.setAttribute('marktype', data.type);
					draw && draw(elem);
				});
			}
		},
		
		_drawExchange: function(data) {
			var index = 0;
			var points = data && data.points || this.innerData.points;
			var text = data && data.content.replace(/\n/g, '');
			return function fn(elem) {
				var nodes = Array.prototype.slice.call(elem.childNodes);
				for(var i = 0; i < nodes.length; i++) {
					var node = nodes[i];
					if(node.nodeType === 3 && !hasOnlyLinefeed(node.nodeValue)) {
						var value = node.nodeValue;
						var fNode = document.createDocumentFragment();
						for(var _i = 0; _i < value.length; _i++) {
							var className = '';
							var iElem = document.createElement('i');
							iElem.innerHTML = value.charAt(_i);
							if(index == 0) {
								className = 'left';
							} else if(index === text.length - 1) {
								className = 'right';
							}
							_op.addClass(iElem, className);
							if(index == points[0]) {
								className = 'focus focus1';
							} else if(points[1] && index === points[1] + 1) {
								className = 'focus focus2';
							} else if(index < points[0] || points[1] && index > points[1] + 1) {
								className = 'top';
							} else {
								className = 'bottom';
							}
							_op.addClass(iElem, className);
							iElem.setAttribute('marktype', data.type);
							fNode.appendChild(iElem);
							index++;
						}
						node.parentNode.replaceChild(fNode, node);
					} else if(node.nodeType === 1) {
						fn(node);
					}
				}
			};
		},
		
		addClass: function(elem, cls) {
			if(!_op.hasClass(elem, cls)) {
				elem.className = elem.className == "" ? cls : elem.className + " " + cls;
			}
		},
		
		hasClass: function(elem, cls) {
			cls = cls || "";
			if(cls.replace(/\s/g, "").length == 0) return false; //当cls没有参数时，返回false
			return new RegExp(" " + cls + " ").test(" " + elem.className + " ");
		},
		
		_getData: function(startElem, endElem) {
			var sum = 0;
			var content = '';
			var startOffset = null;
			var endOffset = null;
			var length = null;
			var count = function count(nodes) {
				for(var i = 0; i < nodes.length; i++) {
					var node = nodes[i];
					if(endOffset !== null) {
						break;
					}
					if(node.nodeType === 3 && !_op.hasOnlyLinefeed(node.nodeValue)) {
						var text = _op.removeExtraSpace(node.nodeValue);
						sum += text.length;
						content += startOffset !== null ? text : '';
					} else if(node.nodeType === 1) {
						if(node === startElem) {
							startOffset = sum;
						}
						if(node === endElem) {
							var t = node.innerText;
							endOffset = sum + t.length;
							length = endOffset - startOffset;
							content += t;
						}
						count(node.childNodes);
						if(!endOffset && _op.hasNodeName(node, 'p')) {
							sum++;
							content += '\n';
						}
					}
				}
			};
			count(document.getElementById($this.attr("id")).childNodes);
			return {
				content: content.trim(),
				startOffset: startOffset,
				endOffset: endOffset,
				length: length
			};
		},
		
		removeExtraSpace: function(text) {
			if(typeof text === 'string') {
				text = text.replace(/\u200B/g, '');
			}
			return text;
		},
		
		// 获取批注框html
		getNowSkyeyeAnnoBox: function(params){
			var zIndex = _op.checkIsNull(params.zIndex) ? _op._showEditBoxZIndex : params.zIndex;
			return '<div class="new-skyeye-anno-box" data-text="' + params.selectText + '" data-zIndex="' + zIndex + '" startAdd="' + params.startAdd 
						+ '" endAdd="' + params.endAdd + '" id="' + params.annoId + '" '
						+ '" textLength="' + params.textLength + '"'
						+ ' insId="' + params.insId + '" style="z-index: ' + zIndex + '; margin-top:' + params.marginTop + '">' +
						'<div class="anno-title">' +
							'<img src="' + params.userImage + '" class="anno-user-img"/>' +
							'<font class="anno-user-name">' + params.userName + '</font>' +
							'<font class="anno-time">' + params.createDate + '</font>' +
						'</div>' +
						'<div class="anno-content">' +
							'<div class="show-content" style="display: none">' + params.annoTateContent + '</div>' +
							'<div class="show-editor" contenteditable="true">' + params.annoTateContent + '</div>' +
						'</div>' +
					'</div>';
		},
		
		// 创建标记标签
		createTag: function(tagName, options, insId){
			var selection = options && options.selection || window.getSelection();
			return _op._createTag(selection, insId);
		},
		
		// 构造创建标记的数据
		_createTag: function(selection, insId){
			var newNodeList = [];
			if(selection.rangeCount > 0) {
				var range = selection.getRangeAt(0);
				var snode = range.startContainer;
				var enode = range.endContainer;
				if(snode && enode) {
					if(snode === enode || snode.parentNode === enode.parentNode) {
						var newnode = _op._createMarkElement(insId);
						range.surroundContents(newnode);
						newNodeList.push(newnode);
					} else {
						var arr = _op._surroundCrossContents(range, insId);
						newNodeList = newNodeList.concat(arr);
					}
				} else if(!snode) {
					console.error('range.startContainer does not exist');
				} else if(!enode) {
					console.error('range.endContainer does not exist');
				}
				selection.removeAllRanges();
			}
			return newNodeList;
		},
		
		_surroundCrossContents: function(range, insId){
			var _this = this;
			var newRange = _op._getNewRange(range);
			var nodeList = newRange.nodeList;
			var startOffset = newRange.startOffset;
			var endOffset = newRange.endOffset;
			var length = nodeList.length;
			var newNodeList = [];
			nodeList.forEach(function(node, index) {
				var pnode = node.parentNode;
				var value = node.nodeValue;
				var newnode = _op._createMarkElement(insId);
				if(index === 0) {
					if(node.nodeType === 3) {
						var siblingnode = node.nextSibling;
						newnode.innerText = value.substr(startOffset);
						node.nodeValue = value.substr(0, startOffset);
						if(siblingnode) {
							pnode.insertBefore(newnode, siblingnode);
						} else {
							pnode.appendChild(newnode);
						}
						newNodeList.push(newnode);
					}
				} else if(index === length - 1) {
					if(node.nodeType === 3) {
						var _siblingnode = node.previousSibling;
						newnode.innerText = value.substr(0, endOffset);
						node.nodeValue = value.substr(endOffset);
						if(_siblingnode) {
							_op.insertAfter(newnode, _siblingnode);
						} else {
							pnode.insertBefore(newnode, node);
						}
						newNodeList.push(newnode);
					}
				} else {
					if(node.nodeType === 3) { 
						newnode.innerText = value;
						pnode.replaceChild(newnode, node);
					} else {
						newnode.innerHTML = node.innerHTML;
						node.innerHTML = '';
						node.appendChild(newnode);
					}
					newNodeList.push(newnode);
				}
			});
			return newNodeList;
		},
		
		insertAfter: function(newnode, node) {
			var parent = node.parentNode;
			if(parent.lastChild == node) {
				parent.appendChild(newnode);
			} else {
				parent.insertBefore(newnode, node.nextSibling);
			}
		},
		
		hasNodeName: function(elem, name) {
			return new RegExp("^".concat(name, "$"), 'i').test(elem.nodeName);
		},
		
		_getNewRange: function(range){
			var cnode = range.commonAncestorContainer;
			var snode = range.startContainer;
			var enode = range.endContainer;
			var nodeList = [];
			var start = false;
			var end = false;

			function cb(parent) {
				var childNodes = parent.childNodes;
				for(var i = 0; i < childNodes.length; i++) {
					var child = childNodes[i];
					if(end) {
						break;
					}
					if(child === snode) {
						start = true;
					}
					if(child === enode) {
						end = true;
					}
					if(child.nodeType === 1) {
						if(child.contains(snode) || child.contains(enode) || child.childNodes.length > 0) {
							cb(child);
						} else if(start) {
							nodeList.push(child);
						}
					} else if(child.nodeType === 3 && !_op.hasOnlyLinefeed(child.nodeValue) && start) {
						nodeList.push(child);
					}
				}
			}

			cb(cnode);
			return {
				nodeList: nodeList,
				startOffset: range.startOffset,
				endOffset: range.endOffset
			};
		},
		
		_createMarkElement: function(insId){
			var tagName = _op.tagName;
			var node = document.createElement(tagName);
			node.className = "selectClass " + insId;
			node.style.backgroundColor = '';
			return node;
		},
		
		// 清除不可见的空字符
		hasOnlyLinefeed: function(value){
			return /^(\s*)\n+(\s*)$/.test(value);
		},
		
		// 获取选中的文本
		getSelectText: function(){
			var selectedText;
			if(window.getSelection) {
				selectedText = window.getSelection().toString();
			} else if(document.selection && document.selection.createRange) {
				selectedText = document.selection.createRange().text;
			}
			return selectedText;
		},
		
		// 刷新数据
		resetData: function(deleteNullContent){
			var data = new Array();
			var setting = getObject(_id);
			$.each($this.find(".selectClass"), function(i, item){
				var insId = $.trim($(this).attr("class").replace("selectClass", ""));
				if(_op.inData(data, insId) == -1){
					var _this = $('div[insId="' + insId + '"]');
					var editorContent = _this.find(".show-editor").html();
					if(_op.checkIsNull(editorContent) && deleteNullContent){
						// 取消文字选中
						_op.cancleTextChoose($(this));
						// 如果内容为空则移除
						_this.remove();
					}else{
						_this.find(".show-content").html(editorContent);
						var zIndex = (i + 1);
						_this.css({
							"z-index": zIndex
						});
						var ss = {
							selectText: _this.data("text"),
							annoTateContent: editorContent,
							annoId: _this.attr("id"),
							zIndex: zIndex,
							startAdd: _this.attr("startAdd"),
							endAdd: _this.attr("endAdd"),
							textLength: _this.attr("textLength"),
							insId: _this.attr("insId"),
							userImage: _this.find(".anno-user-img").attr("src"),
							userName: _this.find(".anno-user-name").html(),
							createDate: _this.find(".anno-time").html(),
							marginTop: _this.offset().top
						};
						data.push(ss);
					}
				}
			});
			// 判断是否有批注
			if($("#" + setting.annotateId).find(".new-skyeye-anno-box").length == 0){
				_op.removeAnnoTateBox();
			}
			_op.setSettings(_id, {
				data: data
			});
			// 重置批注列表信息
			_op.resetAnnoBox();
		},
		
		inData: function(data, insId){
			var indexNum = -1;
			$.each(data, function(i, item){
				if(item.insId == insId){
					indexNum = i;
					return false;
				}
			});
			return indexNum;
		},
		
		_getRangeData: function(startOffset, endOffset) {
			var sum = 0;
			var startRange = null;
			var endRange = null;
			var count = function count(nodes) {
				for(var i = 0; i < nodes.length; i++) {
					var node = nodes[i];
					if(endRange !== null) {
						break;
					}
					if(node.nodeType === 3 && !_op.hasOnlyLinefeed(node.nodeValue)) {
						var sum2 = sum;
						var text = _op.removeExtraSpace(node.nodeValue);
						sum += text.length;
						if(!startRange && sum >= startOffset) {
							var offset = startOffset - sum2;
							startRange = {
								node: node,
								offset: offset < 0 ? 0 : offset
							};
						}
						if(!endRange && sum >= endOffset) {
							var _offset = endOffset - sum2;
							endRange = {
								node: node,
								offset: _offset < 0 ? 0 : _offset
							};
						}
					} else if(node.nodeType === 1) {
						count(node.childNodes);
						if(!endRange && _op.hasNodeName(node, 'p')) {
							sum++;
						}
					}
				}
			};
			count(document.getElementById($this.attr("id")).childNodes);
			return {
				startRange: startRange,
				endRange: endRange
			};
		},
		
		// 初始化数据
		initData: function(){
			var setting = getObject(_id);
			if(setting.data.length > 0){
				// 1.加载右侧box
				_op.resetAddAnnotateBox();
				// 重新获取配置信息
				setting = getObject(_id);
				// 2.加载数据批注框
				_op.initDataBox(setting.annotateId, setting.data);
			}
		},
		
		// 加载数据批注框
		initDataBox: function(annotateId, data){
			rangy.init();
			$.each(data, function(i, item){
				var box = _op.getNowSkyeyeAnnoBox({
					selectText: item.selectText,
					startAdd: item.startAdd,
					endAdd: item.endAdd,
					textLength: item.textLength,
					annoId: item.annoId,
					insId: item.insId,
					userImage: item.userImage,
					userName: item.userName,
					zIndex: item.zIndex,
					annoTateContent: item.annoTateContent,
					createDate: item.createDate,
					marginTop: item.marginTop + 'px',
				});
				$("#" + annotateId).append(box);
				_op.loadRange(item);
			});
			window.getSelection().removeAllRanges();
			$("#" + annotateId).find(".show-editor").hide();
			$("#" + annotateId).find(".show-content").show();
		},
		
		loadRange: function(item){
			var selection = window.getSelection();
			var range = _op.getRange();
			var rangeData = _op._getRangeData(item.startAdd, item.endAdd);
			var sr = rangeData.startRange;
			var er = rangeData.endRange;
			try {
				range.setStart(sr.node, sr.offset);
				range.setEnd(er.node, er.offset);
				selection.addRange(range);
			} catch(error) {
				console.error(error);
				console.error("".concat(JSON.stringify(item)));
			}
			var newdata = _op.getSelData(_op.tagName, selection, item.insId, item);
		},
		
		// 获取range对象
		getRange: function(){
			var range;
			if(document.selection){
				// IE
			  	range = document.body.createTextRange(); 
			} else if(window.getSelection){
				// others
			  	range = document.createRange(); 
			} 
			return range;
		},
		
		// 移除包含批注的大box
		removeAnnoTateBox: function(){
			var setting = getObject(_id);
			$("#" + setting.annotateId).remove();
			// 设置当前content的宽度
			var con_width = $this.outerWidth(true);
			var annoTate_width = parseInt(setting.width);
			$this.css({
				"width": (con_width + annoTate_width + 20) + 'px'
			});
			_op.setSettings(_id, {
				whetherLoadData: false,
				annotateId: ""
			});
		},
		
		// 重置批注列表信息
		resetAnnoBox: function(){
			var setting = getObject(_id);
			$.each($("#" + setting.annotateId).find(".new-skyeye-anno-box"), function(i, item) {
				var _this = $(item);
				_this.find(".show-editor").hide();
				_this.find(".show-content").show();
			});
		},

		// 获取随机id
		getRandomId: function(num) {　　
			num = num || 16;　　
			var str = "";
			// 循环产生随机数字串
			for(var i = 0; i < num; i++) {　　　　
				str += Math.floor(Math.random() * 10);　　
			}　　
			return str;
		},
		
		// 判断是否为空
		checkIsNull: function(content){
			if(content == "" || content == null){
				return true;
			}
			return false;
		},
		
		// 取消文字选中
		cancleTextChoose: function(_this){
			_this.prop("outerHTML", _this.html());
		},
		
		// 获取当前时间
		getNowDate: function(){
			var myDate = new Date();
			// 获取当前年
			var year = myDate.getFullYear();
			// 获取当前月
			var month = myDate.getMonth() + 1;
			// 获取当前日
			var date = myDate.getDate();
			var h = myDate.getHours(); // 获取当前小时数(0-23)
			var m = myDate.getMinutes(); // 获取当前分钟数(0-59)
			var s = myDate.getSeconds();
			return year + '-' + _op.getNow(month) + "-" + _op.getNow(date) + " " + _op.getNow(h) + ':' + _op.getNow(m) + ":" + _op.getNow(s);
		},
		
		// 格式化数字为两位数
		getNow: function(s){
			return s < 10 ? '0' + s: s;
		},
		
		// 重置setting
		setSettings: function(id, opt) {
			var set = getObject(id);
			set = $.extend({}, set, opt);
			setObject(id, set);
		}
	}

	// 初始化加载批注插件
	$.fn.skyeyeAnnotate = function(options) {
		if(!$(this).attr("id")) {
			throw err = new Error('Not Find Id');
		}
		options.id = $(this).attr("id");
		var annotate = new skyeyeAnnotate(this, options);
		$.each(skyeye_setting, function(index, item) {
			if(!_op.checkIsNull(item)) {
				if(item.settings.id == annotate.settings.id) {
					skyeye_setting.splice(index, 1);
					return;
				}
			}
		});
		skyeye_setting.push(_createObject(annotate.settings.id, annotate.settings));
		return this.each(function() {
			annotate.init();
		});
	}

	// 获取数据
	$.fn.getAnnotateData = function() {
		if(!$(this).attr("id")) {
			throw err = new Error('Not Find Id');
		}
		return getObject($(this).attr("id")).data;
	}

	// 创建新的批注对象
	var _createObject = function(id, settings) {
		var obj = {
			id: id,
			settings: settings
		};
		return obj;
	}

	// 获取批注对象
	var getObject = function(id) {
		for(var i of skyeye_setting) {
			if(i.id == id) {
				return i.settings;
			}
		}
	}

	// 重置批注对象中的settings
	var setObject = function(id, settings) {
		for(var i of skyeye_setting) {
			if(i.id == id) {
				i.settings = settings;
			}
		}
	}

});